package ConcurrentHashMap_10;
import java.util.concurrent.ConcurrentHashMap;
public class 聚合操作_reduce操作 {
    public static void main(String[] args) {
        final ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
        final int THREAD_COUNT = 15;

        // 初始化数据
        for (int i = 0; i < 100; i++) {
            map.put("key-" + i, i);
        }

        // 创建多个reduce线程
        for (int i = 0; i < THREAD_COUNT; i++) {
            new Thread(new Runnable() {
                public void run() {
                    try {
                        Thread.sleep((long)(Math.random() * 100)); // 模拟处理时间

                        // 并行reduce求和
                        int sum = map.reduceValues(2, (value)->{
                            return value;
                        }, (v1, v2)->{
                            return v1 + v2;
                        });

                        System.out.println(Thread.currentThread().getName() +
                                                   " 计算的部分和: " + sum);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "Reduce线程-" + i).start();
        }

        // 等待所有线程完成
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}